<?php

namespace app\api\admin;

use zhanshop\App;
use zhanshop\console\command\server\Accepted;
use zhanshop\Log;
use zhanshop\ServEvent;
use zhanshop\ShareData;

class BridgEvent extends ServEvent
{
    public function onWorkerStart($server, $workerId) :void{
        App::config()->loadIni();

        if($server->setting){
            if($workerId < $server->setting['worker_num']) {
                $msg = "工作进程启动, 进程".getmypid();
            }else{
                $msg = "任务进程启动, 进程".getmypid();
            }
            Log::errorLog(SWOOLE_LOG_DEBUG, $msg);
        }
        App::log();
        App::webhandle()->setServers($this->servNames)->router(); // webServer处理
    }
    /**
     * 客户端连接到桥接服务
     * @param $server
     * @param $fd
     * @param $reactorId
     * @return void
     */
    public function onConnect($server, $fd, $reactorId) :void
    {
        App::make(Accepted::class)->newConnection($fd);
    }

    protected $num = 0;
    /**
     * 收到桥接消息
     * @param $server
     * @param $fd
     * @param $reactorId
     * @param $data
     * @return void
     */
    public function onReceive($server, $fd, $reactorId, $data) :void
    {
        $connection = App::make(Accepted::class)->getConnection($fd);
        if($connection && $data !== ""){
            $connection->setBuff($data);
            $fullData = &$connection->getBuff();
            try {
                if(strpos($fullData, "\r\n") !== false){
                    $arr = explode("\r\n", $fullData);
                    for($i = 0; $i < count($arr) - 1; ++$i){
                        $rowData = $arr[$i];

                        parent::onReceive($server, $fd, $reactorId, $rowData);

                        $fullData = substr($fullData, strlen($rowData) + 2);
                    }
                }
            }catch (\Throwable $e){
                $fullData = "";
            }
        }
    }

    protected function onLineMessage($server, $fd, $data)
    {
        if($data){
            $toFd = intval(explode('/v1/bridge.message/', $data['uri'])[1]);
            if($toFd){
                $server->send($toFd, base64_decode($data['body'])); // 收得快发得慢
            }
        }
    }

    /**
     * 关闭
     * @param $server
     * @param $fd
     * @param $reactorId
     * @return void
     */
    public function onClose($server, $fd, $reactorId) :void
    {

        App::make(Accepted::class)->closeConnection($fd);

        $fd = strval($fd);
        if(ShareData::exist($fd)){
            ShareData::del($fd);
        }
    }
}
